<template>
  <div class="note-layout" v-loading="loading">
    <div class="note-xmind" v-if="!isLock && !loading">
      <div class="add-xmind-header">
        <BreadCrumb :breadcrumbList="breadcrumbList"></BreadCrumb>
        <div class="right">
          <MoreOperation
            :data="noteDetail"
            :lock="isLock"
            :initLock="initLock"
            @update="updateNote"
          />
        </div>
      </div>
      <el-input
        class="title-input"
        v-model="title"
        @input="handleUpdateTitle"
        placeholder="请输入标题"
      />
      <div class="mind-map">
        <MindMap ref="mindMapRef" :data="data.content" @change="handleChange" />
      </div>
    </div>
    <NoteLock
      v-else-if="!loading && isLock"
      :data="noteDetail"
      @unlock="handleUnlock"
      @update="updateNote"
    ></NoteLock>
  </div>
</template>
<script setup>
import { debounce } from '@/utils/tools.ts'
import BreadCrumb from './components/BreadCrumb.vue'
import { reactive, ref, watch, provide, watchEffect } from 'vue'
import { useRoute } from 'vue-router'
import {
  httpCreateNoteRelation,
  httpDeleteNoteRelation,
  httpGetNoteDetail,
  httpUpdateNote,
} from '@/api/note'
import MindMap from '@/components/mind-map/Index.vue'
import MoreOperation from './components/MoreOperation.vue'
import NoteLock from './components/NoteLock.vue'
import { jsonToObject } from '@/utils/index.js'
import useNoteStore from '@/stores/note'
import { storeToRefs } from 'pinia'
import { flatTree, removeFieldFromTree } from '@/utils/tools.ts'
const noteState = useNoteStore()
const { noteData } = storeToRefs(noteState)

const data = reactive({
  content: {
    data: {
      text: '根节点',
    },
    children: [],
  },
})
const route = useRoute()
const title = ref('')
const noteDetail = ref({}) // 当前笔记所有信息
const breadcrumbList = ref([])
const editId = ref()
const mindMapRef = ref()
const mmChangeData = ref()
const isLock = ref(false)
const initLock = ref(false)
const associations = ref([])
const labels = ref([])

const handleUnlock = (value) => {
  isLock.value = false
  if (value === 'remove') {
    initLock.value = false
  }
}
const updateNote = () => {
  getNoteDetail()
}
const searchParent = (arr, id) => {
  let breadCrumbs = []
  let obj = arr.find((item) => {
    return item.id == id
  })
  if (obj) {
    breadCrumbs.push(obj)
    breadCrumbs = breadCrumbs.concat(searchParent(arr, obj.pid))
  }
  return breadCrumbs
}
watchEffect(() => {
  let cloneArr = JSON.parse(JSON.stringify(noteData.value))
  let flatArr = flatTree(cloneArr)
  const searchArr = searchParent(flatArr, route.params.mindmapId)
  breadcrumbList.value = searchArr.reverse()
  if (breadcrumbList.value.length) {
    title.value = breadcrumbList.value[breadcrumbList.value.length - 1].label
  }
})
const updateBreadcrumb = async () => {
  const res = await httpGetNoteDetail({
    fd_id: route.params.mindmapId,
  })
  const { list } = res
  if (list.length) {
    // const { crumb } = list[0]
    // let arr = crumb.reverse()
    // arr[0] && arr[0].parent_id === 0 && (arr[0].name = '全部笔记')
    // breadcrumbList.value = arr
    noteDetail.value = list[0]
  }
}
provide('updateBreadcrumb', updateBreadcrumb)
const loading = ref(true)
const getNoteDetail = async () => {
  loading.value = true
  const res = await httpGetNoteDetail({
    fd_id: route.params.mindmapId,
  })
  const { list } = res
  if (list.length) {
    const { is_lockbox, crumb } = list[0]
    noteDetail.value = list[0]
    // title.value = list[0].title
    editId.value = list[0].id
    isLock.value = !!is_lockbox
    initLock.value = !!is_lockbox
    // let arr = crumb.reverse()
    labels.value = list[0].label?.map((x) => x.label_id)
    // arr[0] && arr[0].parent_id === 0 && (arr[0].name = '全部笔记')
    // breadcrumbList.value = arr
    // if (list[0].content) {
    data.content = list[0].content
      ? JSON.parse(list[0].content)
      : {
          data: {
            text: '根节点',
          },
          children: [],
        }
    // }
    associations.value = getContentAssociations(data.content)
  }
  loading.value = false
}
const handleUpdateTitle = debounce(async () => {
  const res = await httpUpdateNote({
    fd_id: editId.value,
    title: title.value,
    content: mmChangeData.value
      ? JSON.stringify(mmChangeData.value)
      : JSON.stringify(data.content),
    label_id_list: labels.value,
  })
  if (res) {
    noteState.getFolderListData()
  }
}, 300)

const handleChange = async (value) => {
  let data = removeFieldFromTree([value], '_node')[0]
  // mmChangeData.value = value
  mmChangeData.value = data
  await httpUpdateNote({
    fd_id: editId.value,
    title: title.value,
    content: JSON.stringify(data),
    label_id_list: labels.value,
  })
  updateAssociations(value)
}

const getContentAssociations = (contentValue) => {
  let associationsArr = []
  const { data, children } = contentValue
  if (children && children.length) {
    children.forEach((child) => {
      associationsArr = associationsArr.concat(getContentAssociations(child))
    })
  }
  const { hyperlinkTitle } = data
  if (hyperlinkTitle) {
    const hyperlinkTitleObj = jsonToObject(hyperlinkTitle)
    if (hyperlinkTitleObj && hyperlinkTitleObj.id) {
      associationsArr.push(hyperlinkTitleObj.id)
    }
  }
  return associationsArr
}

const updateAssociations = (result) => {
  const arr = getContentAssociations(result)
  if (arr.sort().join() !== associations.value.sort().join()) {
    arr.forEach((id1) => {
      if (associations.value.indexOf(id1) < 0) {
        httpCreateNoteRelation({
          source_id: route.params.mindmapId,
          target_id: id1,
        }).catch(() => null)
      }
    })
    associations.value.forEach((id2) => {
      if (arr.indexOf(id2) < 0) {
        httpDeleteNoteRelation({
          source_id: route.params.mindmapId,
          target_id: id2,
        }).catch(() => null)
      }
    })
    associations.value = arr
  }
}

watch(
  () => route.params.mindmapId,
  () => {
    getNoteDetail()
  },
  {
    immediate: true,
  },
)
</script>
<style scoped lang="scss">
.mind-map {
  height: calc(100vh - 103px);
  width: 100%;
}

.title-input {
  background: rgb(250, 250, 250);

  :deep(.el-input__wrapper) {
    background-color: #fafafa;
    box-shadow: none !important;
    font-size: 18px;
    color: #000;
    font-weight: 600;
  }

  ::-webkit-input-placeholder {
    font-size: 14px;
  }

  :-moz-placeholder {
    font-size: 14px;
  }

  :-ms-input-placeholder {
    font-size: 14px;
  }

  :deep(.el-input__inner) {
    color: #000;
  }
}

.add-xmind-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.note-layout {
  height: 100%;
}
</style>
